package com.gitee.huanminabc.dynamicdb.data;

import com.gitee.huanminabc.dynamicdb.config.DynamicDbSpringConfig;
import com.gitee.huanminabc.dynamicdb.core.DBSwatchUtil;
import com.gitee.huanminabc.dynamicdb.dal.dao.TenantManager;
import com.gitee.huanminabc.dynamicdb.entity.TenantEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.DependsOn;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: java-huanmin-utils
 * @description: 数据库租户添加 优先级大于配置文件
 * @author: huanmin
 * @create: 2024-12-11 10:29
 **/
@DependsOn("abstractRoutingDataSource")
@Slf4j
public class TenantInitialize implements ApplicationRunner {
    @Autowired(required = false)
    private TenantManager tenantManager;
    @Autowired
    private DynamicDbSpringConfig dynamicDbSpringConfig;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (dynamicDbSpringConfig.isDatabaseLoadActivate()){
            log.info("-----------------TenantInitialize------------------");
            Map<String, Map<String, String>> tenant1 = dynamicDbSpringConfig.getTenants();
            try {
                DBSwatchUtil.toggleDB(dynamicDbSpringConfig.getMultiTenantLoadKey(),()->{
                    List<TenantEntity> tenants = tenantManager.getTenants();
                    for (TenantEntity tenant : tenants) {
                        Map<String, String> stringStringMap = tenant1.get(tenant.getTenantKey());
                        if (stringStringMap != null) {
                            stringStringMap.put(tenant.getDatasourceKey(),tenant.getDatasourceAsKey());
                        }else{
                            Map<String, String> newMap=new HashMap<>();
                            newMap.put(tenant.getDatasourceKey(),tenant.getDatasourceAsKey());
                            tenant1.put(tenant.getTenantKey(),newMap);
                        }
                    }
                    return  null;
                });
            } catch (Throwable e) {
                log.error("[TenantInitialize->run] 初始化租户失败",e);
                System.exit(1);
            }
        }
    }
}
